package com.bwie.home.backstage.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bwie.home.backstage.config.GuliESConfig;
import com.bwie.home.backstage.util.UUIDUtil;
import com.bwie.home.common.utils.R;
import org.apache.catalina.User;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.home.common.utils.PageUtils;
import com.bwie.home.common.utils.Query;

import com.bwie.home.backstage.dao.UserDao;
import com.bwie.home.backstage.entity.UserEntity;
import com.bwie.home.backstage.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RedisTemplate redisTemplate;

    //引入es 依赖
    @Autowired
    private RestHighLevelClient client;

    @Override
    public R queryPage(Map<String, Object> params, UserEntity userEntity) {
        R ok =R.ok();
        ArrayList<UserEntity> list1 = new ArrayList<>();
        //1.同步es数据
        List<UserEntity> list = baseMapper.selectList(null);

        for (UserEntity e : list) {
            IndexRequest request = new IndexRequest("usera");
            request.id(e.getUserId()+"");
            String jsonString = JSON.toJSONString(e);
            request.source(jsonString, XContentType.JSON);

            //同步执行
            try {
                IndexResponse indexResponse = client.index(request, GuliESConfig.COMMON_OPTIONS);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }

        //取出es数据 模糊查询
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("usera"); //去索引
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); //条件查询
        if (userEntity!=null){
            //根据名称查
            if (userEntity.getUserName()!=null && !userEntity.getUserName().equals("")){
                MatchQueryBuilder username = QueryBuilders.matchQuery("userName", userEntity.getUserName());
                boolQueryBuilder.must(username);
            }
             //es 高亮
            if (userEntity.getUserName()!=null && !userEntity.getUserName().equals("")){
                HighlightBuilder highlightBuilder = new HighlightBuilder();
                highlightBuilder.postTags("<span style='color: red'>");
                highlightBuilder.preTags("</span>");
                HighlightBuilder.Field highlightTitle =
                        new HighlightBuilder.Field("userName");
                highlightTitle.highlighterType("unified");
                highlightBuilder.field(highlightTitle);
                searchSourceBuilder.highlighter(highlightBuilder);

            }

            searchSourceBuilder.query(boolQueryBuilder);
            //分页
            Integer pageIndex =Integer.valueOf((String) params.get("pageIndex"));
            Integer pageSize =Integer.valueOf((String) params.get("pageSize"));
            searchSourceBuilder.from((pageIndex-1)*pageSize);
            searchSourceBuilder.size(pageSize);
            searchRequest.source(searchSourceBuilder);
            //异步执行查询条件
            try {
                SearchResponse searchResponse = client.search(searchRequest, GuliESConfig.COMMON_OPTIONS);
                SearchHits hits = searchResponse.getHits();
                long value=hits.getTotalHits().value;
                SearchHit[] hits1 = hits.getHits();
//                SearchHits hits = searchResponse.getHits();
                for (SearchHit hit : hits1) {
                    UserEntity entity = JSONObject.parseObject(hit.getSourceAsString(), UserEntity.class);
                    Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                    if (userEntity.getUserName()!=null && !userEntity.getUserName().equals("")){
                        HighlightField highlight = highlightFields.get("userName");
                        Text[] fragments = highlight.fragments();
                        String fragmentString = fragments[0].string();
                        entity.setUserName(fragmentString);
                    }
                    list1.add(entity);
                }
//                List<UserEntity> collect = Arrays.stream(hits1).map(aaa -> {
//                    UserEntity entity = JSONObject.parseObject(aaa.getSourceAsString(), UserEntity.class);
//                    return entity;
//                }).collect(Collectors.toList());
                ok.put("list",list1).put("total",value);
            } catch (IOException e) {
                e.printStackTrace();
            }

            return ok;
        }








//        for (UserEntity e : list) {
//
//        }
//        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
//        if (userEntity!=null){
//            if (userEntity.getUserName()!=null && !userEntity.getUserName().equals("")){
//                wrapper.like("user_name",userEntity.getUserName());
//            }
//            if (userEntity.getUserPhone()!=null && !userEntity.getUserPhone().equals("")){
//                 wrapper.like("user_phone",userEntity.getUserPhone());
//            }
//        }
//        IPage<UserEntity> page = this.page(
//                new Query<UserEntity>().getPage(params),
//                wrapper
//
//        );

        return null;
    }

    /**
     *  手机号 密码登录
     */
    @Override
    public UserEntity phoneLogin(UserEntity userEntity, HttpServletRequest request, HttpServletResponse response) {
        UserEntity userEntity1 = baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("user_phone", userEntity.getUserPhone()).
                eq("user_pwd", userEntity.getUserPwd()));
        if (userEntity1!=null){
            //生成cookie
            String ticket = UUIDUtil.uuid();
            //将用户信息存入 redis中
            redisTemplate.opsForValue().set("bbbb"+ticket,userEntity1);
            request.getSession().setAttribute(ticket,userEntity1);
//            CookieUtil.setCookie(request,response,"userTicket",ticket);
            return userEntity1;
        }
        return null;
    }


    /**
     *   手机号 验证登录
     */
    @Override
    public UserEntity phone(String phone, String code) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("user_phone",phone));
    }


}